﻿@page "/counter"
@using BlazorApp.Services
@inject IJSRuntime JSRuntime
@rendermode InteractiveServer

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

<button onclick="callDotNetMethods()">点我(静态方法)</button>

<button @onclick="CallJsWithDotNetObject">点我(实例方法)</button>

@code {
    private int currentCount = 0;

    [Parameter]
    public int IncrementAmount { get; set; } = 1;

    private void IncrementCount()
    {
        currentCount += IncrementAmount;
    }

    private IJSObjectReference? _jsModule;

    // 修正：添加正确的重写签名
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // 加载 JS 模块(动态加载)
            _jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./exportmethod.js");
            Console.WriteLine(_jsModule);
        }
    }

    private async Task CallJsWithDotNetObject()
    {
        if (_jsModule is not null)
        {
            // 创建一个 JsService 的实例
            var dotNetObject = new JsService("MyComponent");

            // 创建一个 JS 可以持有的 .NET 对象引用
            var dotNetObjectReference = DotNetObjectReference.Create(dotNetObject);

            // 调用 JS 函数，并将引用传递过去
            await _jsModule.InvokeVoidAsync("jsFunctionThatCallsDotNet", dotNetObjectReference);
        }
    }

    public async ValueTask DisposeAsync()
    {
        if (_jsModule is not null)
        {
            await _jsModule.DisposeAsync();
        }
        // dotNetObjectReference 通常由 JS 调用 dispose 后自动清理
    }


    public partial class MyComponent : ComponentBase
    {
        // 方法 1: 使用默认名称 (类名.方法名)
        [JSInvokable("GetGreetingAsync")]
        public static Task<string> GetGreetingAsync(string name)
        {
            return Task.FromResult($"Hello, {name}! Welcome from .NET.");
        }

        // 方法 2: 使用自定义标识符
        [JSInvokable("calculateSum")]
        public static int CalculateSum(int a, int b)
        {
            return a + b;
        }
    }
}
